// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
require('../config')
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import 'element-ui/lib/theme-default/index.css'
import axios from 'axios'
import Qs from 'qs'
import Icon from 'vue-awesome/components/Icon'
import util from './assets/js/util'
import {Message,Row, Col,Form,FormItem,Pagination,Input,Tag,Button,Dropdown,
  DropdownMenu,DropdownItem,Menu,Submenu,MenuItem,Breadcrumb,BreadcrumbItem,
  Table,TableColumn,Radio,Checkbox,CheckboxGroup,Dialog} from 'element-ui'
import 'vue-awesome/icons/home'
import 'vue-awesome/icons/list-alt'
import 'vue-awesome/icons/list'
import 'vue-awesome/icons/tags'

Vue.use(Row)
Vue.use(Col)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Pagination)
Vue.use(Input)
Vue.use(Tag)
Vue.use(Button)
Vue.use(Dropdown)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)
Vue.use(Menu)
Vue.use(Submenu)
Vue.use(MenuItem)
Vue.use(Breadcrumb)
Vue.use(BreadcrumbItem)
Vue.use(Table)
Vue.use(TableColumn)
Vue.use(Radio)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(Dialog)
Vue.component('icon', Icon)
Vue.config.productionTip = false

util.authcode = util.getSession('authcode') ? util.getSession('authcode') : util.getCookie('authcode')
util.serverUrl = process.env.NODE_ENV === 'production' ? 'https://dev.edaoe.com' : 'http://localhost'

util.api = axios.create({
  baseURL: util.serverUrl,
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  transformRequest: [function (data) {
    if (!data)
      data = {}
    if (!data.hasOwnProperty("username"))
      data.authcode = util.authcode
    data = Qs.stringify(data, {arrayFormat: 'brackets'})
    return data
  }]
})

util.api.interceptors.response.use(response => {
  let data = response.data
  if (!data.isOk) {
    switch (data.errno) {
      case -1:
        Message.error('服务器异常')
        break
      case -2:
        Message.error('认证失败，请重新登录')
        util.clearAuth()
        util.vue.$router.push('/login')
        break
    }
  }
  return data
}, function (error) {
  Message.error('服务器连接失败！')
  return Promise.reject(error)
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    if (util.authcode)
      next('/layout/index')
    else
      next()
  } else {
    if (util.authcode)
      next()
    else
      next('/login')
  }
})

util.vue = new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: {App}
})
